package ua.org.gtug.android;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.PlusRequest;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;

public class MainActivity extends SherlockActivity implements OnItemClickListener {

	private static final String TAG = "kgc";
	private static final int REQUEST_AUTHENTICATE = 1;
	private static final int DIALOG_ACCOUNTS = 1;
	private static final String PREF = "prefs";

	private Authenticator authenticator;
	private final GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(null);
	private Plus plusClient;

	private ListView newsList;
	private AsyncTask<?, ?, ?> updateNewsTask;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.main);

		newsList = (ListView) findViewById(R.id.news_list);
		newsList.setOnItemClickListener(this);

		plusClient = Plus.builder(AndroidHttp.newCompatibleTransport(), new GsonFactory())
				.setApplicationName("Kyiv GTUG Center Android app")
				.setHttpRequestInitializer(accessProtectedResource)
				.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
					@Override
					public void initialize(final JsonHttpRequest request) throws IOException {
						final PlusRequest plusRequest = (PlusRequest) request;
						plusRequest.setKey(getString(R.string.google_api_key));
					}
				})
				.build();

		authenticator = new Authenticator(this,
				getSharedPreferences(PREF, MODE_PRIVATE),
				DIALOG_ACCOUNTS, REQUEST_AUTHENTICATE) {
			@Override
			public void onAuthenticated(final String accessToken) {
				accessProtectedResource.setAccessToken(accessToken);
				new UpdateNewsTask().execute();
			}
		};
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (!authenticator.isAuthenticated()) {
			authenticator.authenticate();
		}
	}

	@Override
	protected void onPause() {
		if (updateNewsTask != null) {
			updateNewsTask.cancel(true);
		}

		super.onPause();
	}



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.main_menu, menu);
        // Calling super after populating the menu is necessary here to ensure that the action bar helpers have a chance to handle this event.
        return super.onCreateOptionsMenu(menu);
    }

	private class UpdateNewsTask extends AsyncTask<Void, Void, List<Activity>> {
		private boolean repeat = false;

		@Override
		protected void onPreExecute() {
			if (updateNewsTask != null) {
				updateNewsTask.cancel(true);
			}
			updateNewsTask = this;
			setSupportProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected List<Activity> doInBackground(final Void... params) {
			try {
				final Plus.Activities.List list = plusClient.activities().list("110301321530950732281", "public");
				list.setMaxResults(20L);
				list.setFields("nextPageToken,items(url,object/content)");
				final ActivityFeed feed = list.execute();
				final List<Activity> items = feed.getItems();
				final List<Activity> filteredItems = new ArrayList<Activity>(items.size());
				for (final Activity activity : items) {
					if (activity.getPlusObject().getContent().trim().length() > 0) {
						filteredItems.add(activity);
					}
				}

				return filteredItems;
			} catch (final GoogleJsonResponseException e) {
				if (e.getDetails().code == 401) {
					repeat = true;
					authenticator.invalidate();
				} else {
					Log.e(TAG, "Request failed", e);
				}

				return null;
			} catch (final IOException e) {
				Log.e(TAG, "Request failed", e);
				return null;
			}
		}

		@Override
		protected void onPostExecute(final List<Activity> items) {
			updateNewsTask = null;
			setSupportProgressBarIndeterminateVisibility(false);
			if (items != null) {
				newsList.setAdapter(new FeedNewsAdapter(items));
			}
			if (repeat) {
				authenticator.authenticate();
			}
		}
	}

	private class FeedNewsAdapter extends BaseAdapter {
		private final List<Activity> items;

		public FeedNewsAdapter(final List<Activity> items) {
			this.items = items;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(final int position) {
			return items.get(position);
		}

		@Override
		public long getItemId(final int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, final ViewGroup parent) {
			if (view == null) {
				view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, parent, false);
				view.getLayoutParams().height = WRAP_CONTENT;
			}

			final Activity item = (Activity) getItem(position);

			((TextView) view.findViewById(android.R.id.text1)).setText(Html.fromHtml(item.getPlusObject().getContent()));

			return view;
		}

	}

	@Override
	public void onItemClick(final AdapterView<?> adapterView, final View view, final int position, final long id) {
		final Activity item = (Activity) adapterView.getAdapter().getItem(position);
		final String url = item.getUrl();
		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
	}

	@Override
	protected Dialog onCreateDialog(final int id) {
		switch (id) {
			case DIALOG_ACCOUNTS:
				return authenticator.onCreateDialog();
		}
		return null;
	}

	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case REQUEST_AUTHENTICATE:
				authenticator.onActivityResult(resultCode);
				break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
				break;
			case R.id.menu_refresh:
				Toast.makeText(this, "Fake refreshing...", Toast.LENGTH_SHORT).show();
				setSupportProgressBarIndeterminateVisibility(true);
				getWindow().getDecorView().postDelayed(
					new Runnable() {
						@Override
						public void run() {
							setSupportProgressBarIndeterminateVisibility(false);
						}
					}, 1000);
				break;
		}
		return super.onOptionsItemSelected(item);
	}

}